package tool

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	//"io"
)

type AesEncrypt struct {
	Key string
}

func (this *AesEncrypt) getKey() []byte {
	keyLen := len(this.Key)
	if keyLen < 16 {
		panic("res key 长度不能小于16")
	}
	arrKey := []byte(this.Key)
	if keyLen >= 32 {
		//取前32个字节
		return arrKey[:32]
	}
	if keyLen >= 24 {
		//取前24个字节
		return arrKey[:24]
	}
	//取前16个字节
	return arrKey[:16]
}

func (this *AesEncrypt) Encrypt(text string) string {
	key := this.getKey()
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	ciphertext := make([]byte, aes.BlockSize+len([]byte(text)))
	iv := ciphertext[:aes.BlockSize]
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(text))
	return base64.StdEncoding.EncodeToString(ciphertext)
}

func (this *AesEncrypt) Decrypt(b64 string) string {
	key := this.getKey()
	text, err := base64.StdEncoding.DecodeString(b64)
	if err != nil {
		panic(err)
	}
	//text := decodeBase64(b64)
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	if len(text) < aes.BlockSize {
		panic("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	return string(text)
}
